//
//  SkillChoiceViewController.m
//  RosettaApplication2
//
//  Created by Taylor White on 11/21/13.
//  Copyright (c) 2013 Miami University. All rights reserved.
//

#import "SkillChoiceViewController.h"

@interface SkillChoiceViewController ()

@end

@implementation SkillChoiceViewController
@synthesize table_ok,rosetta_db,dataList,my_column_names,numberOfRows,db_open_status,m_tableView,skillTable;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    UIColor* rosettaBlue = [UIColor colorWithRed:0x00/255.0f
                                           green:0xCD/255.0f
                                            blue:0xFF/255.0f alpha:1];
    
    [super viewDidLoad];
    // DB TUTORIAL
    
    dataList = [[NSMutableArray alloc] init];
    numberOfRows = 0;
    rosetta_db      = @"rosetta.sqlite";
    skillTable      = @"skill";
    db_open_status  = NO;
    table_ok        = NO;
    my_column_names = [[NSArray alloc]initWithObjects:@"skill_id",@"name", nil];
    
    if ([self openDBWithSQLName:rosetta_db]) {
        db_open_status = YES;
        if(![self createTable:skillTable WithColumns:my_column_names]) {
            UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Warning" message:@"The table has NOT been created" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:Nil, nil];
            [av show];
        } else {
            table_ok = YES;
        }
        
    }
    // DB TUTORIAL END
    
    
    #define rows 3
    #define columns 3
    
    skills = 0;
    
    for(int i = 0; i < 3; i ++){
        selected[i] = -1;
    
    }
    
    int i = 0;
    for(int y = 0; y < 4; y++)
    {
        for(int x = 0; x < 4;x++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(60 + 170 * x, 350 + 150 * y, 160, 90);
            unsigned buttonNumber = y * 3 + x;
            button.tag = buttonNumber;
            button.titleLabel. numberOfLines = 3; // Dynamic number of lines
            button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
            button.titleLabel.highlighted=false;
            button.titleLabel.textAlignment=UITextAlignmentCenter;
            [button setHighlighted:false]; // no affect
            [button setBackgroundColor:[UIColor whiteColor]];
            button.adjustsImageWhenHighlighted=NO; // No affect
            button.titleLabel.font = [UIFont systemFontOfSize:20];
            [button setTitleColor:rosettaBlue forState:UIControlStateNormal];
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            
            NSString *skillNum = [NSString stringWithFormat:@"%@%u", @"option", i];
            NSString *thisSkill = [defaults objectForKey:skillNum];
            
            NSLog(@"selected[0] %@ ", thisSkill);
            
            [button setTitle:[NSString stringWithFormat:@"%@", thisSkill] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview: button];
            i++;
        }
        
    }
    
}


-(IBAction)saveButton:(id)sender {
    if (table_ok) {
        if (!db_open_status) {
            [self openDBWithSQLName:rosetta_db];
        }
        NSMutableDictionary *objectColsVals = [[NSMutableDictionary alloc] init];
        for (id aSubView in [self.view subviews]) {
            if ([aSubView isKindOfClass:[UITextField class]]) {
                if([(UITextField *)aSubView isFirstResponder]) {
                    [(UITextField *)aSubView resignFirstResponder];
                }
                int this_tag = ((UITextField *)aSubView).tag;
                NSString *this_textValue = [(UITextField*)aSubView text];
                [objectColsVals setValue:this_textValue forKey: [my_column_names objectAtIndex:this_tag]];
                ((UITextField *)aSubView).text = @"";
            }
        }
        if ([[objectColsVals allKeys] count] >0) {
            if ([self addItemstoTable:skillTable WithColumnValues:objectColsVals]) {
                [self closeDB];
            }
        }
    }
}

-(IBAction)fetchButton:(id)sender {
    [dataList removeAllObjects];
    NSString *fetch_sql = [NSString stringWithFormat:@"SELECT * FROM %@",skillTable];
    
    if(!db_open_status) {
        [self openDBWithSQLName:rosetta_db];
        db_open_status = YES;
    }
    sqlite3_stmt * statement;
    if (sqlite3_prepare_v2(inputDbName, [fetch_sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        int numberOfColumns = sqlite3_column_count(statement);
        while(sqlite3_step(statement) == SQLITE_ROW) {
            NSString *result_output = @"";
            for (int a = 1; a < numberOfColumns; a++) {
                char *field = (char *) sqlite3_column_text(statement,a);
                NSString *fieldVal = [[NSString alloc] initWithUTF8String:field];
                NSString *formatOut = [NSString stringWithFormat:@"%@ ", fieldVal];
                result_output = [result_output stringByAppendingString:formatOut];
            }
            [dataList addObject:result_output];
        }
    }
    [self closeDB];
    numberOfRows = [dataList count];
    [m_tableView reloadData];
}

#pragma tableView methods
-(NSInteger)numberOfSectionsInTableView: (UITableView *) tableView {
    return 1;
}

-(NSInteger) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section {
    return numberOfRows;
}

-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"MainCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if ([dataList count] > 0) {
        cell.textLabel.text = [dataList objectAtIndex:indexPath.row];
    }
    
    return cell;
}


#pragma sqlite methods
-(BOOL) openDBWithSQLName:(NSString *)sqlname{
    BOOL is_Opened = NO;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *my_sqlfile = [[paths objectAtIndex:0]
                            stringByAppendingPathComponent:sqlname];
    if (sqlite3_open([my_sqlfile UTF8String], &inputDbName) == SQLITE_OK) {
        is_Opened = YES;
    }
    return is_Opened;
}

-(BOOL) createTable:(NSString *) tablename WithColumns:(NSArray *)columnNames {
    BOOL hasBeenCreated = NO;
    NSString * fieldSet = @"";
    char *err;
    for (int a =0; a<[columnNames count];a++) {
        NSString *columnSet = [NSString stringWithFormat:@"'%@' TEXT",[columnNames objectAtIndex:a]];
        fieldSet = [fieldSet stringByAppendingString:columnSet];
        if(a<([columnNames count]-1)) {
            fieldSet = [fieldSet stringByAppendingString:@","];
        }
    }
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (ID INTEGER PRIMARY KEY AUTOINCREMENT,%@);",rosetta_db,fieldSet];
    if(sqlite3_exec(inputDbName, [sql UTF8String],NULL,NULL, &err) != SQLITE_OK) { // if not okay, close
        sqlite3_close(inputDbName);
    } else {
        hasBeenCreated = YES;
    }
    
    return hasBeenCreated;
}

-(BOOL) addItemstoTable:(NSString *)usetable WithColumnValues:(NSDictionary *)valueObject {
    BOOL hasBeenAdded = NO;
    NSString *myColumns = @"";
    NSString *myValues = @"";
    // Loop through all the value keys from the user entered form data and
    // create col and val for sql statement
    for (int r=0; r<[[valueObject allKeys] count]; r++) {
        NSString *this_keyname = [[valueObject allKeys]objectAtIndex:r];
        myColumns = [myColumns stringByAppendingString:this_keyname];
        NSString *thisval = [NSString stringWithFormat:@"'%@'", [valueObject objectForKey: this_keyname]];
        myValues = [myValues stringByAppendingString:thisval];
        // Add commas to seperate the col and cal lists vefore the last item
        if(r<(([[valueObject allKeys] count])-1)) {
            myColumns = [myColumns stringByAppendingString:@","];
            myValues = [myValues stringByAppendingString:@","];
            
        }
    }
    NSString *myinsert = [NSString stringWithFormat:@"INSERT INTO %@(%@)VALUES (%@)", usetable,myColumns,myValues];
    char *err;
    if(sqlite3_exec(inputDbName, [myinsert UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(inputDbName);
    } else {
        hasBeenAdded = YES;
    }
    
    return hasBeenAdded;
    
}

-(void) closeDB {
    sqlite3_close(inputDbName);
    db_open_status = NO;
    
}
@end
